/* header 登录转换 */
let uidn = localStorage.getItem('uid');
if (uidn != null) {
    let username = localStorage.getItem('username');
    $('#login').html(username).click(function(){
        var userRes = confirm('是否要退出登录');
        if(userRes == true){
            localStorage.removeItem('uid');
            localStorage.removeItem('username');
            location.href = './carts.html';
        }
    })
}else{
    $('#login').html('登录').click(function(){
        location.href = './login.html'
    })
}

/* nav下拉跳转 */
$("#nav div ul").on('click', 'li', function () {
    localStorage.setItem('pclass', $(this).attr('pclass'));
    localStorage.setItem('pid', $(this).attr('pid'));
    location.href = './infor.html';
})


/* load */
// let id = null;
let uid = localStorage.getItem('uid');
load();
function load() {
    if (uid == null) {
        alert("请先登录方可查看购物车");
    } else {
        let html = '';
        cartsAPI = `http://localhost:3000/carts?uid=${uid}`;
        axios.get(cartsAPI)/* 找到属于某个用户的购物车 */
            .then(function (res) {
                for (let i = 0; i < res.data.length; i++) {/* 循环找到购物车内的所有信息 */
                    // id = i;
                    let pnum = res.data[i].pnum;
                    let id = res.data[i].id;
                    let url = `http://localhost:3000/${res.data[i].pclass}/${res.data[i].pid}`
                    axios.get(url)/* 通过pclass/pid找到商品的详细信息 */
                        .then(function (res) {
                            html = `<li pid="${res.data.id}" pclass="${res.data.pclass}" id="${id}">
                                <input type="checkbox" name="" id="" class="singel">
                                <img src="${res.data.img[0]}" alt="">
                                <div>
                                    <h2>${res.data.title}</h2>
                                    <p>${res.data.intro}</p>
                                    <span>${res.data.price}</span>
                                    <br>
                                    <button class="sub" pid="${res.data.id}" pclass="${res.data.pclass}">-</button><b>${pnum}</b><button class="add" pid="${res.data.id}" pclass="${res.data.pclass}">+</button>
                                    <button class="del" pid="${res.data.id}" pclass="${res.data.pclass}">删除</button>
                                </div>
                            </li>`;
                            html = $('#main ul').html() + html;
                            $('#main ul').html(html);
                            /* 计算价格数量 */
                            allCount();
                        })
                }
            })
    }
}
/* carts修改 */
/* add */
$("#main ul").on("click", ".add", function () {
    let pnum = $(this).prev().html()
    pnum++;
    $(this).prev().html(pnum)
    let id = $(this).parent().parent().attr("id");
    let altelAPI = `http://localhost:3000/carts/${id}`;
    axios({
        method: "patch",
        url: altelAPI,
        data: {
            pnum
        }
    }).then((res) => {
        console.log('修改成功');
        /* 重新计算价格数量 */
        count();
    })
})
/* sub */
$("#main ul").on("click", ".sub", function () {
    let pnum = $(this).next().html()
    if (pnum <= 1) {
        let res = confirm('购物车数量不可以小于1,是否要选择删除');
        if (res == true) {
            let id = $(this).parent().parent().attr("id");
            console.log(id)
            let delAPI = `http://localhost:3000/carts/${id}`;
            axios({
                method: "delete",
                url: delAPI,
            }).then((res) => {
                console.log('删除成功');
                $(this).parent().parent().remove();
                /* 重新计算价格数量 */
                count();
            })
        }else{
            pnum = 1;
        }
    } else {
        pnum--;
        $(this).next().html(pnum)
        let id = $(this).parent().parent().attr("id");
        let altelAPI = `http://localhost:3000/carts/${id}`;
        axios({
            method: "patch",
            url: altelAPI,
            data: {
                pnum
            }
        }).then((res) => {
            console.log('修改成功');
            /* 重新计算价格数量 */
            count();
        })
    }
})

/* 商品删除 del*/
$("#main ul").on("click", ".del", function () {
    let id = $(this).parent().parent().attr("id");
    console.log(id)
    let delAPI = `http://localhost:3000/carts/${id}`;
    axios({
        method: "delete",
        url: delAPI,
    }).then((res) => {
        console.log('删除成功');
        $(this).parent().parent().remove();
        /* 重新计算价格数量 */
        count();
    })
})


/* checkbox */

function allCount() {
    /* all */
    $('#main').on('click', '.all', function () {
        $('#main ul li [type=checkbox]').prop('checked', this.checked);
        count();
    })
    /* singel */
    $('#main').on('click', '.singel', function () {
        let flag = true;
        $(this).parent().parent().attr('checked', this.checked);
        $('#main ul li').each(function (v) {
            if ($($('#main ul li')[v]).find('[type=checkbox').prop('checked') == false) {
                flag = false;
            }
        })
        $('#main .all').prop('checked', flag)
        count();
    })
}


/* 数量价格计算 */
function count() {
    var num = 0;
    var pri = 0;
    $('#main ul li').each(function (v) {
        if ($($('#main ul li')[v]).find('[type=checkbox').prop('checked') == true) {
            var arr = $($('#main ul li')[v]).find('div').find('span').html().split('');
            arr.shift();
            str = arr.join('');
            num += parseInt($($('#main ul li')[v]).find('div').find('b').html());
            pri += parseInt(str) * parseInt($($('#main ul li')[v]).find('div').find('b').html());
        }
    })
    pri = '￥'+ pri;
    $("#main div #num").html(num);
    $("#main div #pri").html(pri);
}


/* 生成订单 */
$("#main div button").click(function(){
    let cookArr = [];
    $('#main ul li').each(function (v) {
        var obj = {};
        if ($($('#main ul li')[v]).find('[type=checkbox').prop('checked') == true) {
            // console.log($($('#main ul li')[v]).find('img').attr('src'))
            obj.img = $($('#main ul li')[v]).find('img').attr('src');
            obj.title = $($('#main ul li')[v]).find('div h2').html();
            obj.price = $($('#main ul li')[v]).find('div span').html();
            obj.pnum = $($('#main ul li')[v]).find('div b').html();
            cookArr.push(obj)
            console.log(obj)
        }
    })
    console.log(cookArr)
    localStorage.setItem('orderList',JSON.stringify(cookArr))
    localStorage.setItem('num',$("#main div #num").html());
    localStorage.setItem('pri',$("#main div #pri").html());
    location.href = './order.html';
})
